import json
import re

from django import http
from django.contrib.auth import authenticate, login

from django.shortcuts import render, redirect

# Create your views here.
# 1, 注册页面视图
from django.views import View
from django_redis import get_redis_connection
from requests import session

from ihome.apps.users.models import User
from ihome.utils import constants
from ihome.utils.response_code import RET

#1,注册页面
class RegisterView(View):

    def post(self,request):
        #1, 获取参数
        data_dict = json.loads(request.body.decode())
        mobile = data_dict.get("mobile")
        password = data_dict.get("password")
        phonecode = data_dict.get("phonecode")
        #2, 校验参数
        #2,1 为空校验
        if not all([mobile,phonecode,password]):
            return http.HttpResponseForbidden("参数不全")

        #2,3 手机号格式正确
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return http.HttpResponseForbidden("手机号格式有误")

        #2,5 短信验证码正确(下一次完成)
        redis_conn = get_redis_connection("code")
        redis_sms_code = redis_conn.get("sms_code_%s"%mobile)
        if phonecode != redis_sms_code.decode():
            return http.HttpResponseForbidden("短信验证码填写错误")


        #3, 数据入库
        user = User.objects.create_user(password=password,mobile=mobile,username=mobile)

        response = http.JsonResponse({'errno': RET.OK, 'errmsg': '注册成功'})

        # 4,返回响应
        return response


#4, 登录视图
class LoginView(View):

    def post(self,request):
        #1,获取参数
        data_dict = json.loads(request.body.decode())
        mobile = data_dict.get("mobile")
        password = data_dict.get("password")

        #2,校验参数
        #2,1 为空校验
        if not all([mobile,password]):
            return http.JsonResponse({'errno':RET.NECESSARYPARAMERR,'errmsg':' 参数不全'})

        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return http.JsonResponse({'errno':RET.DATAERR,'errmsg':'手机号有误'})

        # count = User.objects.filter(mobile = mobile).count()
        # if not count:
        #     return http.JsonResponse({'errno':RET.NODATA,'errmsg':'账号不存在'})

        #2,3 密码格式校验
        if not re.match(r'^[0-9A-Za-z]{8,20}$',password):
            return http.JsonResponse({'errno':RET.DATAERR,'errmsg':'密码格式不对'})
        #2,4 账号密码正确性校验, 如果认证成功返回用户对象, 不成功返回None
        user = authenticate(request, username=mobile, password=password)
        if not user:
            return http.JsonResponse({'errno':RET.DATAERR,'errmsg':'账号或密码不正确'})

        # 3,数据入库(状态保持)
        login(request, user)  # 就是将用户的信息存储在session
        request.session.set_expiry(constants.REDIS_SESSION_COOKIE_EXPIRES)  # 两天
        response = http.JsonResponse({'errno':RET.OK,'errmsg':'登陆成功'})
        response.set_cookie("username",user.username,max_age=constants.REDIS_SESSION_COOKIE_EXPIRES)

        #4,返回响应
        return response

    def get(self,request):
        username = request.user.username,
        username = str(username)
        if request.user.is_authenticated:
            return http.JsonResponse({'errno':RET.OK,
                                      'errmsg':'已登陆',
                                      "data": { "name": username}
                                      })
        else:
            return http.JsonResponse({'errno': RET.DBERR,
                                      'errmsg': '未登陆',
                                      })


class AreasView(View):
    def get(self,request):
        response = http.JsonResponse({
        "errmsg": "获取成功",
        "errno": "0",
        "data": [
            {
                "aid": 1,
                "aname": "东城区"
            },
            {
                "aid": 2,
                "aname": "西城区"
            },
            {
                "aid": 3,
                "aname": "朝阳区"
            }
        ]
        })
        return response

class UserView(View):
    def get(self,request):
        response = http.JsonResponse({
                                "data": {
                                    "avatar": "http://oyucyko3w.bkt.clouddn.com/FmWZRObXNX6TdC8D688AjmDAoVrS",
                                    "create_time": "2017-11-07 01:10:21",
                                    "mobile": "18599998888",
                                    "name": "哈哈哈哈哈哈",
                                    "user_id": 1
                                },
                                "errmsg": "OK",
                                "errno": "0"
        })
        return response

#上传头像
class HeadPngView(View):
    def post(self,request):
        data_dict = json.loads(request.body.decode())
        avatar = data_dict.get("avatar")

        response = http.JsonResponse({
            "data": {
                "avatar": "http://oyucyko3w.bkt.clouddn.com/FmWZRObXNX6TdC8D688AjmDAoVrS",
                "create_time": "2017-11-07 01:10:21",
                "mobile": "18599998888",
                "name": "哈哈哈哈哈哈",
                "user_id": 1
            },
            "errmsg": "OK",
            "errno": "0"
        })

        return response

#修改用户名
class NameView(View):
    def put(self,request):
        #1,获取参数
        data_dict = json.loads(request.body.decode())
        name = data_dict.get("name")

        #2,校验参数

        #3,数据入库
        request.user.set_username(name)
        request.user.save()

        #4,返回参数
        response = http.JsonResponse({'errno': RET.OK, 'errmsg': '修改成功'})
        return response

#用户实名认证
class AuthView(View):
    def post(self,request):
        # 1,获取参数
        data_dict = json.loads(request.body.decode())
        real_name = data_dict.get("real_name")
        id_card = data_dict.get("id_card")

        # 2,校验参数
        # 2,1 为空校验
        if not all([real_name, id_card]):
            return http.JsonResponse({'errno': RET.NECESSARYPARAMERR, 'errmsg': ' 参数不全'})

        # 3,数据入库
        user = User.objects.update(real_name=real_name,id_card=id_card)

        # 4,返回参数
        response = http.JsonResponse({'errno': RET.OK, 'errmsg': '修改成功'})
        return response




